﻿using System.Collections.Generic;
using UnityEngine;
using Microsoft.MixedReality.Toolkit.Utilities;
using GDGeek;
using System;

namespace Shows_3D
{
    public class CustomServiceList : MonoBehaviour
    {
        [SerializeField] private Shows3DNetworkDiscovery networkDiscovery;
        [SerializeField] private GameObject background;
        [SerializeField] private GameObject list;
        [SerializeField] private GameObject csiPrototype; //item 原型

        private readonly Dictionary<long, Shows3DServerResponse> _servers = new Dictionary<long, Shows3DServerResponse>();

        private void Update()
        {
            
        }

        /// <summary>
        /// 删除list节点下所有子节点
        /// </summary>
        private void DeleteAllItem()
        {
            while (list.transform.childCount > 0)
            {
                DestroyImmediate(list.transform.GetChild(0).gameObject);
            }
        }
        
        /// <summary>
        /// 刷新在线客服的列表
        /// </summary>
        private void Refresh()
        {
            //删除所有子节点，还原背景
            DeleteAllItem();
            background.transform.localScale = Vector3.one;
            //刷新背景长度
            background.transform.localScale = new Vector3(1, _servers.Count, 1);
            foreach (Shows3DServerResponse info in _servers.Values)
            {
                GameObject itemObj = Instantiate(csiPrototype, list.transform);
                CustomServiceItem itemInfo = itemObj.GetComponent<CustomServiceItem>();
                itemInfo.Init(info);
                list.GetComponent<GridObjectCollection>().UpdateCollection();
            }
        }
        
        /// <summary>
        /// 注册到networkDiscovery 的 OnServerFound
        /// </summary>
        /// <param name="info"></param>
        public void OnDiscoveredServer(Shows3DServerResponse info)
        {
            if (_servers.ContainsKey(info.serverId)) return;
            _servers[info.serverId] = info;
            Refresh();
        }

        public void Clear()
        {
            _servers.Clear();
        }
    }
}